#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 创建QTcpSocket对象
    m_socket = new QTcpSocket(this);

    // 连接信号与槽
    connect(m_socket, &QTcpSocket::connected, this, &MainWindow::onConnected);
    connect(m_socket, &QTcpSocket::readyRead, this, &MainWindow::onReadyRead);
    connect(m_socket, &QTcpSocket::disconnected, this, &MainWindow::onDisconnected);
}

MainWindow::~MainWindow()
{
    delete ui;
    if(m_socket)
    {
        m_socket->disconnected();
        delete m_socket;
        m_socket = nullptr;
    }
}

void MainWindow::onConnected()
{
    qDebug() << "Connected to server!";
    ui->label_2->setText(QStringLiteral("服务器已连接"));
}

void MainWindow::onReadyRead()
{
    QByteArray response = m_socket->readAll();
    qDebug() << "Received from server:" << response;
    // 解析JSON数据
    QJsonDocument doc = QJsonDocument::fromJson(response);
    if (doc.isObject()) {
        QJsonObject jsonObject = doc.object();
        ui->plainTextEdit->appendPlainText(QString("req_cmd_type:%1").arg(jsonObject["req_cmd_type"].toInt()));
        ui->plainTextEdit->appendPlainText(QString("result:%1").arg(jsonObject["result"].toInt()));
        ui->plainTextEdit->appendPlainText(QString("description:%1").arg(jsonObject["description"].toString()));
    }
}

void MainWindow::onDisconnected()
{
    qDebug() << "Disconnected from server!";
    ui->label_2->setText(QStringLiteral("服务器已断开"));
}

void MainWindow::on_pushButton_clicked()
{
    // 连接到服务器
    m_socket->connectToHost("127.0.0.1", 8000);
}

void MainWindow::on_pushButton_2_clicked()
{
    // 准备JSON数据
    QJsonObject jsonObject;
    jsonObject["cmd_type"] = 1;
    jsonObject["data"] = "some data";
    jsonObject["seq_cmd"] = 12345;

    // 创建QJsonDocument
    QJsonDocument doc(jsonObject);

    // 将JSON数据转换为字节数组
    QByteArray data = doc.toJson();

    // 发送数据
    m_socket->write(data);
    m_socket->flush();
}
